package com.wantupai.translate.utils;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;

import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.wantupai.translate.App;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import static com.wantupai.translate.Constant.ImagePath;

public class SspShareUtils {
    public static final String AUTHORITY = "com.ume.browser.fileprovider";

    public void share(Activity activity, String shareUrl, String title, String desc, Bitmap shareBitmap, int type) {
        if (type == 0 || type == 1) {
            WXWebpageObject webpage = new WXWebpageObject();
            webpage.webpageUrl = shareUrl;
            final WXMediaMessage msg = new WXMediaMessage(webpage);
            msg.title = title;
            msg.description = desc;
            Bitmap thumbBitmap = Bitmap.createScaledBitmap(shareBitmap, 150, 150, true);
            MyLog.e("ShareUtils", bmpToByteArray(thumbBitmap).length + " 分享图片长度");
            msg.thumbData = bmpToByteArray(thumbBitmap);
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = "webpage" + title + type;
            req.message = msg;
            if (type == 1) {
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
            } else {
                req.scene = SendMessageToWX.Req.WXSceneSession;
            }
            App.getWeChatApi().sendReq(req);
        } else if (type == 2) {
//            Bitmap thumbBitmap = Bitmap.createScaledBitmap(shareBitmap, 150, 150, true);
            String path = saveBitmap(activity.getApplicationContext(), shareBitmap);
            SspQqUtils.getInstance(activity.getApplicationContext()).shareImgAndWords(activity, shareUrl, path, title, desc, new SspQqUtils.ShareOnResult() {
                @Override
                public void onSuccess() {
                    ToastUtils.show("分享成功");
                }

                @Override
                public void onFail(String error) {

                }
            });
        }
    }


    public void shareImg(Activity activity, Bitmap shareBitmap, int type) {
        if (type == 1 || type == 0) {
            WXImageObject imgObj = new WXImageObject(shareBitmap);
            WXMediaMessage msg = new WXMediaMessage();
            msg.mediaObject = imgObj;
            Bitmap thumbBitmap = Bitmap.createScaledBitmap(shareBitmap, 320, 320, true);
            msg.thumbData = bmpToByteArray(thumbBitmap);
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = "imgshare" + type;
            req.message = msg;
            if (type == 1) {
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
            } else {
                req.scene = SendMessageToWX.Req.WXSceneSession;
            }
            App.getWeChatApi().sendReq(req);
        } else if (type == 2) {
            String path = saveBitmap(activity.getApplicationContext(), shareBitmap);
            SspQqUtils.getInstance(activity.getApplicationContext()).shareImage(activity, path, new SspQqUtils.ShareOnResult() {
                @Override
                public void onSuccess() {
                    ToastUtils.show("分享成功");
                }

                @Override
                public void onFail(String error) {

                }
            });
        }
    }

    public void shareFile(Activity context, String filePath, int type) {

        if (type == 7) {
            Intent intent = new Intent();
            ComponentName cop = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
            intent.setComponent(cop);
            intent.setAction(Intent.ACTION_SEND);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(context, SspShareUtils.AUTHORITY, new File(filePath));
            } else {
                uri = Uri.fromFile(new File(filePath));
            }

            intent.putExtra(Intent.EXTRA_STREAM, uri);  //传输图片或者文件 采用流的方式
            intent.setType("*application/pdf*");   //分享文件
            context.startActivity(Intent.createChooser(intent, "来自万图拍的分享"));

        } else if (type == 1 || type == 2 || type == 3) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filePath)));  //传输图片或者文件 采用流的方式
            intent.setType("*/*");   //分享文件
            context.startActivity(Intent.createChooser(intent, "来自万图拍的分享"));
        } else if (type == 2) {
            Intent intent = new Intent("android.intent.action.SEND");
            intent.setComponent(new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity"));
            intent.setType("*/*");
            intent.putExtra(Intent.EXTRA_SUBJECT, "来自万图拍的分享");
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filePath)));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }


    public void shareText(Activity context, String text, int type) {
        if (type == 0) {
            Intent intent = new Intent();
            ComponentName cop = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
            intent.setComponent(cop);
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra("android.intent.extra.TEXT", text);
//            intent.putExtra("sms_body", content);
            intent.putExtra("Kdescription", !TextUtils.isEmpty(text) ? text : "");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);

        } else if (type == 1) {
            Intent intent = new Intent();
            //分享精确到微信的页面，朋友圈页面，或者选择好友分享页面
            ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
            intent.setComponent(comp);
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra("android.intent.extra.TEXT", text);
//            intent.putExtra("sms_body", content);
            intent.putExtra("Kdescription", !TextUtils.isEmpty(text) ? text : "");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else if (type == 2) {
            Intent intent = new Intent("android.intent.action.SEND");
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, "来自万图拍的分享");
            intent.putExtra(Intent.EXTRA_TEXT, text);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity"));
            context.startActivity(intent);

        }

        /*if (type == 1 || type == 0) {
            WXTextObject txtObj = new WXTextObject(text);
            WXMediaMessage msg = new WXMediaMessage(txtObj);
            msg.title = "";
            msg.description = "";
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = "txtshare" + type;
            req.message = msg;
            if (type == 1) {
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
            } else {
                req.scene = SendMessageToWX.Req.WXSceneSession;
            }
            SousouApi.getWeChatApi().sendReq(req);
        } else if (type == 2) {
            //SspQqUtils.getInstance(activity.getApplicationContext()).shareTxt(activity, text, null);
        }*/
    }


    public Bitmap createViewBitmap(View v) {
        try {
            int w = v.getMeasuredWidth();
            int h = v.getMeasuredHeight();
            Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(bmp);
            c.drawColor(Color.WHITE);
            /*如果不设置canvas画布为白色，则生成透明 */
            v.layout(0, 0, w, h);
            v.draw(c);
            return bmp;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public byte[] bmpToByteArray(Bitmap bitmap) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
        int options = 100;
        while (output.toByteArray().length > 32 && options != 10) {
            output.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, output);
            options -= 10;
        }
        return output.toByteArray();
    }

    private static String generateFileName() {
        return UUID.randomUUID().toString();
    }

    public static String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath;
        File filePic;
        savePath = ImagePath;
        try {
            filePic = new File(savePath + generateFileName() + ".jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

        return filePic.getAbsolutePath();
    }
}
